<template>
  <div class="audit">
    <el-row class="auditButton">
      <el-button
        :size="size"
        v-for="(item, index) in buttonOption"
        :key="index"
        :plain="status !== item.status"
        :type="item.type"
        @click="handleViewed(item.status)">{{item.name}} ({{item.number}})</el-button>
      <el-button
        v-if="this.buttonOption.length !== 0"
        :size="size"
        @click="handleShowForm">更多条件</el-button>
    </el-row>
    <el-row>
      <el-col>
        <transition name="fade">
          <el-form
            v-if="isShow"
            :size="size"
            ref="form"
            :model="form"
            label-width="70px"
            inline
            class="auditForm">
            <el-form-item>
              <treeselect
                  v-model="form.depart"
                  :clearable="true"
                  placeholder="请选择科室"
                  noChildrenText="不好意思哟~,没有下一级了~~"
                  :normalizer="normalizer"
                  :options="departOptions"
                  style="width:150px"
                  />
            </el-form-item>
            <el-form-item>
              <el-select v-model="form.type"
                placeholder="请选择日期类型">
                <el-option
                  v-for="item in dateTypeOptions"
                  :key="item.dictId"
                  :label="item.dictName"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-date-picker
                style="width: 190px;"
                v-model="form.startTime"
                type="date"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
                placeholder="请选择开始日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item>至</el-form-item>
            <el-form-item>
              <el-date-picker
                style="width: 190px;"
                v-model="form.endTime"
                type="date"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
                placeholder="请选择结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-input v-model="form.cases"
                placeholder="请输入姓名或住院/门诊号"
                clearable>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-input v-model="form.diseases"
                placeholder="请输入传染病名"
                clearable>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                :size="size"
                class="button"
                type="primary"
                icon="el-icon-search"
                @click="handleQueryReportView('search')">查询</el-button>
              <el-button
                :size="size"
                class="button"
                type="warning"
                icon="el-icon-position"
                @click="handleExport">导出已审核</el-button>
            </el-form-item>
          </el-form>
        </transition>
      </el-col>
    </el-row>
    <cs-table :table-data="tableData"
              :table-label="tableLabel"
              @handleButton="handleButton"
              :maxHeight="580"
              :loading="loading"
              :isSelection="isSelection"
              :table-option="tableOption">
      <template slot="auditStatus" slot-scope="scope">
        <el-tag v-if="scope.row.auditStatus === 1" :size="size">未审核</el-tag>
        <el-tag v-if="scope.row.auditStatus === 2" :size="size" type="success">已审核</el-tag>
        <el-tag v-if="scope.row.auditStatus === 3" :size="size" type="success">已上报</el-tag>
        <el-tag v-if="scope.row.auditStatus === 4" :size="size" type="warning">未上报</el-tag>
        <el-tag v-if="scope.row.auditStatus === 5" :size="size" type="warning">审核未通过</el-tag>
      </template>
      <template slot="zyidType" slot-scope="scope">
        <el-tag
          :size="size"
          effect="plain"
          :type="scope.row.zyidType === 1 ? '' : 'success'">
          {{scope.row.zyidType === 1 ? '门诊' : '住院'}}</el-tag>
      </template>
    </cs-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNo"
      :page-sizes="[12, 20, 25, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="text-align: right;">
    </el-pagination>
    <!-- 审核提交框 -->
    <view-dialog ref="viewDialog" @handleReportView="handleQueryReportView"></view-dialog>
  </div>
</template>

<script>
import {
  queryReportView,
  deleteReportCard,
  viewReportCard,
  viewDateType,
  exportData
} from '@/api/hospital/reportreview.js'
import { exportExcel } from '@/utils/improtFile.js'
import Cookies from "js-cookie"
import { getDataList } from '@/api/auth/dept.js'
import CsTable from '@/components/cs-table'
import viewDialog from './components/viewDialog'
import { hasPermission } from '@/permission/index.js'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  data () {
    return {
      isShow: false,
      size: window.SITE_CONFIG.tableSize,
      // 按钮循环数据
      buttonOption: [],
      status: "1",
      form: {
        type: 'card.create_time',
        startTime: '',
        endTime: '',
        depart: null,
        cases: '',
        diseases: ''
      },
      departOptions: [],
      dateTypeOptions: [],
      loading: false,
      isSelection: false,
      pageNo: 1,
      pageSize: 12,
      total: 0,
      tableData: [],
      tableLabel: [
        { label: '状态', param: 'auditStatus', align: 'center', sortable: false, isShow: true, slot: true },
        { label: '姓名', param: 'patientname', align: 'center', sortable: false, isShow: true },
        { label: '传染病名', param: 'disease', align: 'center', sortable: false, isShow: true },
        { label: '科室', param: 'depart', align: 'center', sortable: false, isShow: true },
        { label: '类型', param: 'zyidType', align: 'center', sortable: false, isShow: true, slot: true },
        { label: '住院/门诊号', param: 'zyid', align: 'center', sortable: false, isShow: true },
        { label: '上报时间', param: 'createTime', align: 'center', sortable: false, isShow: true }
      ],
      tableOption: {
        label: '操作',
        width: '350',
        options: [
          { label: '查看', type: '', icon: 'el-icon-view', methods: 'view', auth: 'sys:user:view' },
          { label: '编辑', type: 'warning', icon: 'fa fa-edit', methods: 'edit', auth: 'sys:user:update', isShow: true, state: '2,3', stateName: 'auditStatus' },
          // { label: '审核', type: 'primary', icon: 'el-icon-s-order', methods: 'audit', auth: 'sys:user:audit', isShow: true, state: '2,3,5', stateName: 'auditStatus' },
          { label: '删除', type: 'danger', icon: 'el-icon-delete', methods: 'delete', auth: 'sys:user:delete', isShow: true, state: '2,3', stateName: 'auditStatus' },
          { label: '确定已上报', type: 'success', icon: 'el-icon-circle-check', methods: 'isReport', auth: 'sys:user:delete', isShow: true, state: '1,3,5', stateName: 'auditStatus' }
        ]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() >= Date.now() - 8.64e6
        }
      },
      normalizer(node) {
        return {
          id: node.fullName,
          label: node.fullName
        }
      }
    }
  },
  components: {
    CsTable,
    viewDialog,
    Treeselect
  },
  created() {
    this.getDepartData()
    this.getDateType()
    this.handleQueryReportView()
    let that = this
    // 监听浏览器标签页的显示隐藏 --- 控制上报界面返回审核界面的数据刷新
    document.addEventListener('visibilitychange', function() {
      var isHidden = document.hidden
      if (!isHidden) {
        that.handleQueryReportView()
      }
    })
  },
  watch: {
    // 监控页面总数的变化，解决第二页的信息只有一条数据时，进行删除后，页面跳转至第一页，但没有将第一页的数据展示出来
    total(){  // 注意这个函数的名字必须和你监听data中的属性的名字一样，这样才能当你data中的属性发生变化时，触发这个函数
      if(this.total === ((this.pageNo - 1) * this.pageSize) && this.total!=0){ // 这一行是关键代码，倍数关系
          this.pageNo -= 1
          this.handleQueryReportView() // 获取表格数据的方法
      }
    }
  },
  methods: {
    // 导出按钮
    handleExport() {
      // let params = Object.assign({}, this.form)
      // params.depart = params.depart === null ? '' : params.depart
      // let data = {
      //   token: Cookies.get('token'),
      //   ...params
      // }
      // exportExcel('/hp/reportCard/checkExport', data).then(res => {})
      let params = `type=${this.form.type}&startTime=${this.form.startTime}&endTime=${this.form.endTime}&cases=${this.form.cases}&diseases=${this.form.diseases}`
      window.location.href = `${window.SITE_CONFIG['baseUrl']}/hp/reportCard/checkExport?token=${Cookies.get('token')}&${params}`
    },
    // 控制顶部条件显示与隐藏
    handleShowForm() {
      // 每次打开前，清空数据
      this.form.type = 'card.create_time'
      this.form.startTime = ''
      this.form.endTime = ''
      this.form.depart = null
      this.form.cases = ''
      this.form.diseases = ''
      this.isShow = !this.isShow
    },
    // 获取科室数据
    getDepartData () {
      getDataList().then((res) => {
        if (res.code === 200) {
          // res.data.unshift({fullName: '请选择科室', id: ''})
          this.departOptions = res.data
        }
      })
    },
    // 获取字典日期类型数据
    getDateType () {
      viewDateType('dateType').then((res) => {
        if (res.code === 200) this.dateTypeOptions = res.data
      })
    },
    // 头部按钮切换
    handleViewed(val) {
      this.status = val
      this.pageNo = 1
      this.handleQueryReportView()
    },
    // 查询全部数据
    handleQueryReportView(method) {
      if (method === 'search') {
        this.pageNo = 1
      }
      const { type, startTime, endTime, depart, cases, diseases } = this.form
      const { status, pageNo, pageSize } = this
      if (this.form.endTime && this.form.startTime > this.form.endTime) {
        this.$message.warning("结束日期不能小于开始日期")
      } else {
        const data = { type, startTime, endTime, depart, cases, diseases, status, pageNo, pageSize }
        queryReportView(data).then((res) => {
          if (res.code === 200) {
            this.tableData = res.data.pageResult.rows
            this.total = res.data.pageResult.totalRows
            // 上面5个显示数据
            this.buttonOption = res.data.hpStatusVoList
          }
        })
      }
    },
    // 表格操作栏按钮
    handleButton(methods, row, index) {
      if (methods.methods === 'view') {
        this.handleView(methods.row.id)
      } else if (methods.methods === 'edit') {
        this.handleEdit(methods.row.id)
      } else if (methods.methods === 'audit') {
        this.handleAudit(methods.row.id)
      } else if (methods.methods === 'delete') {
        this.handleDelete(methods.row.id)
      } else if (methods.methods === 'isReport') {
        this.handleReport(methods.row.id)
      }
    },
    // 确定已上报
    handleReport(val) {
      const data = {
        id: val,
        auditStatus: '2'
      }
      this.$confirm('确认修改本条数据状态为已上报?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        viewReportCard(data).then((res) => {
          if (res.code === 200) { this.handleQueryReportView() }
        }).catch(() => {
        })
      })
    },
    // 表格操作栏查看
    handleView(val) {
      const newViewUrl = this.$router.resolve({ name: 'reportcard', query: {id: val, type: '1'} })
      window.open(newViewUrl.href,'_blank')
    },
    // 表格操作栏编辑
    handleEdit(val) {
      const newUrl = this.$router.resolve({ name: 'reportcard', query: {id: val, type: '2'} })
      window.open(newUrl.href,'_blank')
    },
    // 表格操作栏审核
    handleAudit(id) {
      this.$refs.viewDialog.init(id, true)
    },
    // 表格操作栏删除
    handleDelete(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteReportCard(id).then((res) => {
          if (res.code === 200) {
            this.handleQueryReportView()
          }
        })
      }).catch(() => {
      })
    },
    // 表格分页参数
    handleSizeChange(newSize) {
      this.pageSize = newSize
      this.handleQueryReportView()
    },
    handleCurrentChange(newPage) {
      this.pageNo = newPage
      this.handleQueryReportView()
    },
    hasPerms: function (perms) {
      // 根据权限标识和外部指示状态进行权限判断
      // return true
      return hasPermission(perms) & !this.disabled
    }
  }
}
</script>

<style scoped>
  .fade-enter-active, .fade-leave-active {
    transition: opacity .5s;
  }
  .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
    opacity: 0;
  }
  .audit {
    padding: 10px;
    text-align: left !important;
  }
  .auditButton {
    margin-bottom: 20px;
  }
  .el-select, .el-input {
    width: 200px !important;
  }
  .el-pagination {
    margin-top: 10px;
  }
</style>
